package org.catspaw.cherubim.lookup;

import java.util.Hashtable;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

public abstract class AbstractJndiLookuper implements Lookuper {

	private Context	context;

	public AbstractJndiLookuper(Context context) {
		this.context = context;
	}

	public AbstractJndiLookuper(Hashtable<?, ?> env) {
		try {
			this.context = new InitialContext(env);
		} catch (NamingException e) {
			throw new LookupException(e);
		}
	}

	public AbstractJndiLookuper() {
		try {
			this.context = new InitialContext();
		} catch (NamingException e) {
			throw new LookupException(e);
		}
	}

	public <T> T lookupInstance(Class<T> interfaceClass) throws LookupException {
		String jndiName = toJndiName(interfaceClass);
		try {
			return (T) context.lookup(jndiName);
		} catch (NamingException e) {
			throw new ImplementationNotFoundException(e);
		}
	}

	public Object lookupInstance(String name) throws LookupException {
		try {
			return context.lookup(name);
		} catch (NamingException e) {
			throw new ImplementationNotFoundException(e);
		}
	}

	protected abstract <T> String toJndiName(Class<T> interfaceClass);

	public Context getContext() {
		return context;
	}
}
